package com.cyt.cytcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyt.cytcrm.entity.DeptRole;
import com.cyt.cytcrm.entity.Role;
import com.cyt.cytcrm.entity.RolePermission;
import com.cyt.cytcrm.mapper.DeptRoleMapper;
import com.cyt.cytcrm.mapper.RoleMapper;
import com.cyt.cytcrm.mapper.RolePermissionMapper;
import com.cyt.cytcrm.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyt.cytcrm.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author PIGS
 * @since 2020-03-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RoleMapper mapper;

    @Autowired
    private DeptRoleMapper deptRoleMapper;

    @Override
    public IPage<Role> selectList(Page<Role> page) {
        return mapper.selectList(page);
    }

    @Override
    public Role selectByName(String roleName) {
        return mapper.selectByName(roleName);
    }

    @Override
    public Integer add(Role role,Integer deptId) {

        role.setCreateTime(StringUtils.getNowTime());
        role.setUpdateTime(role.getCreateTime());  //获取创建时间，可以提高一点性能
        role.setIsDel(0);
        Integer result=mapper.insert(role);
        Integer roleId = role.getRoleId();  //获取插入自增的id
        //将roleId和deptId一同插入到  角色与部门关系表
        DeptRole deptRole = new DeptRole(roleId,deptId);

        deptRole.setCreateTime(StringUtils.getNowTime());
        deptRole.setUpdateTime(deptRole.getCreateTime());  //获取创建时间，可以提高一点性能
        deptRole.setIsDel(0);

        System.out.println("角色部门关系："+deptRole);
       deptRoleMapper.insert(deptRole);

        return result;
    }


    @Override
   public Integer update(Role role,Integer deptId) {

        //设置时间
        role.setUpdateTime(StringUtils.getNowTime());
        //将信息更新到数据库中（空的属性不修改）
        int result =  mapper.updateById(role);


        DeptRole deptRole = new DeptRole(role.getRoleId(),deptId);
        deptRole.setUpdateTime(StringUtils.getNowTime());
        AbstractWrapper wrapper = new QueryWrapper();
        wrapper.eq("role_id",role.getRoleId());
        deptRoleMapper.update(deptRole,wrapper);
        System.out.println("角色部门关系："+deptRole);
        return result;
   }
}
